package com.loto.insurance.mis.web.authority;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.loto.insurance.mis.web.entity.SessionUser;
import com.loto.insurance.mis.web.enumeration.ResultTypeEnum;

public class AuthorityAnnotationInterceptor extends HandlerInterceptorAdapter {

  @Override
  public boolean preHandle(HttpServletRequest request,
	  HttpServletResponse response, Object handler) throws Exception {
	if (handler instanceof HandlerMethod) {
	  HandlerMethod handler2 = (HandlerMethod) handler;
	  INSAuthority misAuthority = handler2
		  .getMethodAnnotation(INSAuthority.class);

	  if (null == misAuthority) {
		// 没有声明权限,放行
		return true;
	  }

	  boolean aflag = false;
	  HttpSession session = request.getSession();
	  SessionUser user = (SessionUser) session.getAttribute("ins_user");
	  if (user != null) {
		// 校验权限
		aflag = AuthorityHelper.hasAuthority(user.getRoleIds(),
		    misAuthority.authorityRole(), user.getUsername(),
		    misAuthority.authorityMenu());
	  }
	  if (false == aflag) {
		if (misAuthority.resultType() == ResultTypeEnum.page) {
		  // 传统的登录页面
		  StringBuilder sb = new StringBuilder();
		  sb.append(request.getContextPath());
		  sb.append("/login?tourl=").append(
			  URLEncoder.encode(
			      request.getRequestURI()
			          + (request.getQueryString() == null ? "" : "?"
			              + request.getQueryString()), "utf-8"));
		  response.sendRedirect(sb.toString());
		} else if (misAuthority.resultType() == ResultTypeEnum.json) {
		  // ajax类型的登录提示
		  /*
	       * response.setCharacterEncoding("utf-8");
	       * response.setHeader("nologin", "nologin");
	       * response.setContentType("application/json"); OutputStream out =
	       * response.getOutputStream(); PrintWriter pw = new PrintWriter(new
	       * OutputStreamWriter(out, "utf-8"));
	       * pw.println("{\"ok\":false,\"msg\":\"" +
	       * ControllerPropertyEnum.NOT_LOGIN + "\"}"); pw.flush(); pw.close();
	       */
		  response.setHeader("nologin", "timeout");
		  response.getWriter().write("nologin");
		}
		return false;
	  }

	}
	return true;
  }
}